window.playerA = new (class PlayerControl {
  // A 选手   B 选手
  constructor(type) {
    this.type = type;
    this.moveEv = new CustomEvent("keydown");
    this.fireEv = new CustomEvent("keydown");
    this.firetimestamp = (new Date()).valueOf()
    this.priority = this.DIRECTION.STOP;
    this.lasttime = 0
  }

  land() {

    // 当前的坦克实例
    var cur = undefined
    var enr = undefined
    aMyTankCount.forEach(element => {
      var c = element
      if(c['id'] == 100)
      {
        cur = c
      }
      if(c['id'] == 200)
      {
        enr = c
      }
    });
    const currentTank = cur
    const enemyTank = enr
    if (!currentTank) return;

    // v
    
    this.action(currentTank)

    this.setName();
  }

  action(currentTank) {
    //如果处于被攻击的危险位置，则优先选择躲避
    if(this.escape(currentTank)){
      console.log("躲避子弹")
      return
    }

    //寻找最近的坦克
    this.findNearestEnemy();
    console.log("寻找附近的坦克")
  }

  //躲避子弹
  escape(currentTank) {
    var posx, posy, spdx, spdy, direAngle, inner, outer, tmpdir, tmpdis, movex, movey
    movex = 0;
    movey = 0;
    for (var i = 0; i < aBulletCount.length; i++) {
      var bullet = aBulletCount[i]
      posx = bullet.X - (currentTank.X + tankWidth / 2)
      posy = (currentTank.Y + tankWidth / 2) - bullet.Y

      direAngle = this.directionToAngle(bullet.direction) 
      spdx = Math.round(Math.cos(direAngle * Math.PI /180))
      spdy = Math.round(Math.sin(direAngle * Math.PI / 180))

      inner = posx * spdx + posy * spdy
      outer = posx * spdy + posy * spdx

      if(inner < 0){
        if ( Math.abs(outer) < 300) {
          var mark = Math.sign(outer);
          if(mark== 0){
            mark = -1;
          }
          tmpdir = (Math.sign(outer) * 90 + direAngle) * Math.PI / 180
          tmpdis = 100 * 2 / Math.sqrt(posx * posx + posy*posy)
          movex+=Math.round(tmpdis * Math.cos(tmpdir))
          movey += Math.round(tmpdis * Math.sin(tmpdir))
        }
      }
    }

    if(!(movex == 0 && movey == 0)){
      var desangle = Math.atan2(movey,movex) * 180 / Math.PI
      console.log("move angle :",desangle)
      this.move(this.angleToDirection(desangle))
      return true;
    } else {
      this.fire()
      return false;
    }

  }

  findNearestEnemy(){

  }
  
  //躲避危险子弹

  //查看附近最近坦克

  // get next coords of current tank for a given direction
  nextTankCoord(direction, currentTank) {
    var nextX = currentTank.X
    var nextY = currentTank.Y

    switch (direction) {
      case this.DIRECTION.UP:
        nextY = currentTank.Y - currentTank.speed < 0 ? 0 : currentTank.Y - currentTank.speed;
        break;
      case this.DIRECTION.DOWN:
        nextY = currentTank.Y + currentTank.speed > screenY - tankWidth ? screenY - tankWidth : currentTank.Y + currentTank.speed;
        break;
      case this.DIRECTION.LEFT:
        nextX = currentTank.X - currentTank.speed < 0 ? 0 : currentTank.X - currentTank.speed;
        break;
      case this.DIRECTION.RIGHT:
        nextX = currentTank.X + currentTank.speed > screenX - tankWidth ? screenX - tankWidth : currentTank.X + currentTank.speed;
        break;
    }

    return [nextX, nextY]
  }

  nextBulletCoord(bullet) {
    var bulletDirection = bullet.direction;
    var bulletSpeed = bullet.speed;
    var bulletX = bullet.X
    var bulletY = bullet.Y

    //get next bullet coord
    if(bulletDirection == 0){
      bulletY -= bulletSpeed;
    }else if(bulletDirection == 1){
      bulletX += bulletSpeed;
    }else if(bulletDirection == 2){
      bulletY += bulletSpeed;
    }else if(bulletDirection == 3){
      bulletX -= bulletSpeed;
    }

    var bulletX = bulletX - bulletWidth / 2;
    var bulletY = bulletY - bulletWidth / 2;

    return [bulletX, bulletY]
  }

  dodgeBullet(currentTank) {
    var tankX, tankY;
    var bulletX, bulletY;
    var collideDir = [0, 0, 0, 0, 0]
    //for each possible next coord of current tank
    for (var dir = 0; dir < 5; dir++) {
      [tankX, tankY] = this.nextTankCoord(dir, currentTank)

      for (var i = 0; i < aBulletCount.length; i++) {
        [bulletX, bulletY] = this.nextBulletCoord(aBulletCount[i])

        var rect = checkCollide(tankX, tankY, tankWidth, tankWidth, bulletX, bulletY, bulletWidth, bulletWidth);
        var isCollide = (rect[2] - rect[0]) * (rect[3] - rect[1]) > 0;
        if (isCollide) {
          collideDir[dir] = 1;
          break;
        }
      }

    }

    console.log(collideDir)

    var direction = 4

    for(var i = 0; i < 5; i++) {
      if (collideDir[i] == 0) {
        direction = i;
        break;
      }
    }
    if(collideDir[4] == 0){
      return 4
    } else {
      //defualt to STOP
    return direction;
    }
    
  }

  leave() {
    this.setName();
    document.onkeyup(this.moveEv);
    document.onkeyup(this.fireEv);
  }
  type;
  // private
  // 方向的别名
  DIRECTION = {
    UP: 0,
    RIGHT: 1,
    DOWN: 2,
    LEFT: 3,
    STOP: 4,
  };
  // 开火事件
  fireEv;
  // 移动事件
  moveEv;


  // 设置队伍
  setName() {
    document.getElementById(
      `Player${this.type === "A" ? 1 : 2}barName`
    ).value = "test1"
    document.getElementById(
      `Player${this.type === "A" ? 1 : 2}Name`
    ).textContent = "test1"
  }
  // 控制移动   举例子：  向左移动： this.move(this.DIRECTION.LEFT)
  move(direction) {
    if (typeof direction === undefined) return;
    this.moveEv.keyCode = this.helpDirectionKeyCode(direction);
    document.onkeydown(this.moveEv);
  }
  // 开火
  fire() {
    this.fireEv.keyCode = this.type === "A" ? 32 : 8;
    document.onkeydown(this.fireEv);
  }

  // 根据玩家返回正确的方向keyCode
  helpDirectionKeyCode(direction) {
    switch (direction) {
      case this.DIRECTION.UP:
        return this.type === "A" ? 87 : 38;
      case this.DIRECTION.DOWN:
        return this.type === "A" ? 83 : 40;
      case this.DIRECTION.LEFT:
        return this.type === "A" ? 65 : 37;
      case this.DIRECTION.RIGHT:
        return this.type === "A" ? 68 : 39;
    }
  }
  
  directionToAngle(direction){
    switch (direction) {
      case this.DIRECTION.UP:
        return 90;
      case this.DIRECTION.DOWN:
        return 270;
      case this.DIRECTION.LEFT:
        return 180;
      case this.DIRECTION.RIGHT:
        return 0;
    }
  }

  angleToDirection(angle) {
    switch ((angle + 360) % 360) {
      case 0:
        return this.DIRECTION.RIGHT;
      case 90:
        return this.DIRECTION.DOWN;
      case 180:
        return this.DIRECTION.LEFT;
      case 270:
        return this.DIRECTION.UP;
    }
  }
})("A");